//更新用户信息
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database() //数据库
const $ = db.command.aggregate
const _ = db.command
const userDynamicList = async function (params) {
  const page = params.page ? params.page - 1 : 0 //当前页
  const number = params.number ? params.number : 10 //单页的数据数量
  const countResult = await db.collection('dynamic').count()
  const total = countResult.total
  const wxContext = cloud.getWXContext()
  //用户是否的判断
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // let listResult = await db.collection('dynamic').skip(page * number).limit(number).get()
  // 聚合查询用户的信息
  const listResult = await db.collection('dynamic').aggregate().match({
      _openid: wxContext.OPENID
    })
    .lookup({
      from: "user",
      let: {
        openid: "$_openid"
      },
      pipeline: $.pipeline().match(_.expr($.eq(['$_openid', '$$openid']))).project({
        _id: 0,
        nickName: 1,
        headPortrait: 1
      }).done(),
      as: "userInfo"
    })
    .lookup({
      from: "dynamicComment",
      localField: '_id',
      foreignField: 'dynamicId',
      as: 'comments'
    }).lookup({
      from: "dynamicEndorse",
      localField: '_id',
      foreignField: 'dynamicId',
      as: 'endorses'
    })
    //是否本人点赞
    .lookup({
      from: "dynamicEndorse",
      let: {
        openid: params._openid?wxContext.OPENID:'',
        dynamicid: "$_id"
      },
      pipeline: $.pipeline().match(_.expr($.and([$.eq(['$_openid', '$$openid']), $.eq(['$dynamicId', '$$dynamicid'])]))).done(),
      as: "isEndorseArr"
    })
    .replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), {
        commentCount: $.size('$comments')
      }, {
        endorseCount: $.size('$endorses')
      },{isEndorse:$.size('$isEndorseArr')}, '$$ROOT'])
    }).project({
      userInfo: 0,
      comments: 0,
      endorses: 0,
      isEndorseArr:0
    })
    .sort({
      createTime: -1
    }).skip(page * number).limit(number)
    .end()

  return {
    data: listResult.list,
    page: page + 1,
    number: number,
    totalPage: batchTimes
  }
}
module.exports = userDynamicList